'use strict';
var domain 	= require('domain');
var express = require('express');
var path 		= require('path');
var bodyParser 		= require('body-parser');
var busboy 				= require('connect-busboy');
var AV 						= require('leanengine');

var http	= require('http');
var ejs 	= require('ejs');

var mdWX	= require('./modules/weixin.js');


//自定义函数及控制器
var cMain		= require('./controllers/main');
var cAdmin	= require('./controllers/admin');
var cAdminNews		= require('./controllers/admin_news');
var cAdminBrand		= require('./controllers/admin_brand');
var cAdminItem		= require('./controllers/admin_item');
var cAdminSetting	= require('./controllers/admin_setting');
var cAdminUser		= require('./controllers/admin_user');
var cAdminImage		= require('./controllers/admin_image');
var cAdminComment	= require('./controllers/admin_comment');


var cloud 	= require('./cloud');





var app 		= express(),
	  admin		= express(),
		client	= express();

// 设置 view 引擎

app.set('views', path.join(__dirname, 'views'));
app.engine('.html', ejs.__express);
app.set('view engine', 'html');

// 设置模板目录
admin.set('views',path.join(__dirname, 'views/admin'));   // 设置模板目录
client.set('views',path.join(__dirname, 'views/client'));   // 设置模板目录

app.use(express.static('public'));

app.use(AV.express());
app.use(busboy());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

// 未处理异常捕获 middleware
app.use((req, res, next) => {
  let d = domain.create();
  d.add(req);
  d.add(res);
  d.on('error', (err) => {
    console.error('uncaughtException url=%s, msg=%s', req.url, err.stack || err.message || err);
    if (!res.finished) {
      res.statusCode = 500;
      res.setHeader('content-type', 'application/json; charset=UTF-8');
      res.end('uncaughtException');
    }
  });
  d.run(next);
});

app.use(AV.Cloud.CookieSession({secret: 'youzhan', maxAge: 3600000,fetchUser:true}));

app.get('/', cMain.homePage);//网站首页

app.get(/^\/(((tmp)|(css))\/)+([a-zA-Z0-9.-_]+(\.html)+)?$/i,cMain.htmlPage);//静态页面

//获取.css及.js文件
app.all(/^\/tmp\/views\/([a-zA-Z0-9\.\-]+((.css)|(.js)))?$/i, function(req,res,next){
	res.type(req.params[1]);
	res.sendfile("/tmp/views/"+req.params[0]);
});

/*
	微信接入
*/
app.all('/wx/cb', mdWX.wxQRCallback);
app.all('/wx/pcb', mdWX.wxPayCallback);

/*
支付宝支付
*/
app.get('/alipay', cMain.doAlipay);
app.get('/alipay/return', cMain.alipayReturnPage);
app.all('/alipay/notify', cMain.alipayNotifyPage);


//获取图片文件
app.use(cMain.doCkAuth);
app.get('/p', cMain.image);
app.get('/login', cMain.loginPage);
app.get('/logout', cMain.logoutPage);
app.get('/register', cMain.registerPage);
app.get('/sysarticle', cMain.articleDetailPage);//网站首页
app.get('/item', cMain.itemListPage);
app.get('/itemdetail', cMain.itemDetailPage);
app.get('/brand', cMain.brandListPage);
app.get('/branddetail', cMain.brandDetailPage);
app.get('/user/collections', cMain.myCollectionsPage);
app.get('/user/cart', cMain.myCartPage);
app.get('/user/bill', cMain.myBillPage);
app.get('/user/setAddress', cMain.setAddressPage);
app.get('/getitems', cMain.doGetItems);
app.get('/getcollections', cMain.doGetCollections);
app.get('/getcartcount', cMain.doGetCartCount);
app.get('/getwxqr', cMain.doGetWXQR);
app.post('/addcollections', cMain.doAddCollections);
app.post('/addcart', cMain.doAddCart);
app.post('/user/createBill', cMain.doCreateBill);
app.post('/user/delcart', cMain.doDelCart);
app.post('/login', cMain.doLogin);
app.post('/register', cMain.doRegister);





/*
后台管理
*/
app.get('/admin-login', cAdmin.loginPage);	//登录页面
app.post('/admin-login', cAdmin.doLogin);	//登录帐号
app.get('/admin-logout',cAdmin.doLogout);	//登出帐号



app.use('/admin', admin);
//admin.use(cAdmin.doSysInit);
admin.use(cAdmin.doCkAuth);					//权限检查
admin.post('/uploadImg', cAdmin.doUploadImage);

admin.get('/index', cAdmin.indexPage);					//后台索引页面
admin.get('/count', cAdmin.ajaxCount);
admin.get('/config/article/list', cAdminSetting.articlePage);
admin.get('/config/article/detail', cAdminSetting.articleDetailPage);
admin.get('/config/homebanner', cAdminSetting.homeBannerPage);
admin.get('/config/homecatagory', cAdminSetting.homeCatagoryPage);
admin.get('/item/list', cAdminItem.listPage);
admin.get('/item/edit', cAdminItem.detailPage);
admin.get('/news/list', cAdminNews.listPage);
admin.get('/news/edit', cAdminNews.detailPage);
admin.get('/brand/list', cAdminBrand.listPage);
admin.get('/brand/edit', cAdminBrand.detailPage);
admin.get('/user/list', cAdminUser.listPage);
admin.get('/user/edit', cAdminUser.detailPage);
admin.get('/image/list', cAdminImage.listPage);
admin.get('/comment/list', cAdminComment.listPage);
admin.post('/config/article/save', cAdminSetting.doSaveArticle);
admin.post('/config/saveBanner', cAdminSetting.doSaveBanner);
admin.post('/config/saveCatagory', cAdminSetting.doSaveCatagory);
admin.post('/item/save', cAdminItem.doSave);
admin.post('/item/delete', cAdminItem.doDelete);
admin.post('/brand/save', cAdminBrand.doSave);
admin.post('/brand/delete', cAdminBrand.doDelete);
admin.post('/user/new', cAdminUser.doCreate);
admin.post('/user/delete', cAdminUser.doDelete);
admin.post('/image/delete', cAdminImage.doDelete);
admin.post('/image/set', cAdminImage.doSet);
admin.post('/comment/delete', cAdminComment.doDelete);
admin.post('/comment/set', cAdminComment.doSet);





// 如果任何路由都没匹配到，则认为 404
// 生成一个异常让后面的 err handler 捕获
app.use(function(req, res, next) {
  res.status(404).render('404.html', {title: 'Sorry, page not found'});
});

// 如果是开发环境，则将异常堆栈输出到页面，方便开发调试
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) { // jshint ignore:line
    var statusCode = err.status || 500;
    if(statusCode === 500) {
      console.error(err.stack || err);
    }
    res.status(statusCode);
    res.render('error', {
      message: err.message || err,
      error: err
    });
  });
}

// 如果是非开发环境，则页面只输出简单的错误信息
app.use(function(err, req, res, next) { // jshint ignore:line
  res.status(err.status || 500);
  res.render('error', {
    message: err.message || err,
    error: {}
  });
});

module.exports = app;
